using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.customers;
using SupplierCustomerManagement.Write.API.Applications.Commands;

namespace SupplierCustomerManagement.Write.API.Controllers
{
    /// <summary>
    /// 客户管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class CustomersController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly IMapper _mapper;
        private readonly ILogger<CustomersController> _logger;

        public CustomersController(
            IMediator mediator,
            IMapper mapper,
            ILogger<CustomersController> logger)
        {
            _mediator = mediator;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 添加客户
        /// </summary>
        /// <param name="command">客户信息</param>
        /// <returns>添加结果</returns>
        [HttpPost]
        public async Task<ApiResult<int>> AddCustomer([FromBody] AddCustomerCommand command)
        {
            try
            {
                // 发送命令
                var result = await _mediator.Send(command);

                if (result.IsSuccess)
                {
                    _logger.LogInformation("成功添加客户，ID: {CustomerId}, 名称: {CustomerName}", 
                        result.data, command.Name);
                }
                else
                {
                    _logger.LogWarning("添加客户失败: {Message}, 名称: {CustomerName}", 
                        result.message, command.Name);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加客户时发生异常，名称: {CustomerName}", command.Name);
                return ApiResult<int>.Error($"添加客户时发生异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 修改客户
        /// </summary>
        /// <param name="command">客户修改信息</param>
        /// <returns>修改结果</returns>
        [HttpPost]
        public async Task<ApiResult<bool>> UpdateCustomer([FromBody] UpdateCustomerCommand command)
        {
            try
            {
                // 发送命令
                var result = await _mediator.Send(command);

                if (result.IsSuccess)
                {
                    _logger.LogInformation("成功修改客户，ID: {CustomerId}, 名称: {CustomerName}", 
                        command.Id, command.Name);
                }
                else
                {
                    _logger.LogWarning("修改客户失败: {Message}, ID: {CustomerId}, 名称: {CustomerName}", 
                        result.message, command.Id, command.Name);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改客户时发生异常，ID: {CustomerId}, 名称: {CustomerName}", 
                    command.Id, command.Name);
                return ApiResult<bool>.Error($"修改客户时发生异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 逻辑删除客户
        /// </summary>
        /// <param name="command">删除客户信息</param>
        /// <returns>删除结果</returns>
        [HttpPost]
        public async Task<ApiResult<bool>> DeleteCustomer([FromBody] DeleteCustomerCommand command)
        {
            try
            {
                // 发送命令
                var result = await _mediator.Send(command);

                if (result.IsSuccess)
                {
                    _logger.LogInformation("成功删除客户，ID: {CustomerId}", command.Id);
                }
                else
                {
                    _logger.LogWarning("删除客户失败: {Message}, ID: {CustomerId}", 
                        result.message, command.Id);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除客户时发生异常，ID: {CustomerId}", command.Id);
                return ApiResult<bool>.Error($"删除客户时发生异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 批量逻辑删除客户
        /// </summary>
        /// <param name="command">批量删除客户信息</param>
        /// <returns>删除结果</returns>
        [HttpPost("batch")]
        public async Task<ApiResult<bool>> BatchDeleteCustomers([FromBody] BatchDeleteCustomersCommand command)
        {
            try
            {
                // 发送命令
                var result = await _mediator.Send(command);

                if (result.IsSuccess)
                {
                    _logger.LogInformation("成功批量删除客户，IDs: {Ids}", 
                        string.Join(",", command.Ids));
                }
                else
                {
                    _logger.LogWarning("批量删除客户失败: {Message}, IDs: {Ids}", 
                        result.message, string.Join(",", command.Ids));
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除客户时发生异常，IDs: {Ids}", string.Join(",", command.Ids));
                return ApiResult<bool>.Error($"批量删除客户时发生异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 上传客户相关图片
        /// </summary>
        /// <param name="imageFile">图片文件</param>
        /// <param name="bucketName">存储桶名称（可选，默认为image）</param>
        /// <param name="prefix">文件前缀（可选，默认为customers）</param>
        /// <returns>上传结果</returns>
        [HttpPost("upload-image")]
        public async Task<ApiResult<string>> UploadCustomerImage(
            IFormFile imageFile,
            string bucketName = "image",
            string prefix = "customers")
        {
            try
            {
                _logger.LogInformation("开始上传客户图片，文件名：{FileName}，存储桶：{BucketName}，前缀：{Prefix}",
                    imageFile?.FileName, bucketName, prefix);

                var command = new UploadImageCommand
                {
                    ImageFile = imageFile,
                    BucketName = bucketName,
                    Prefix = prefix,
                    GenerateUniqueName = true
                };

                var result = await _mediator.Send(command);

                if (result.code == ResultEnumCode.Ok)
                {
                    _logger.LogInformation("客户图片上传成功，URL：{ImageUrl}", result.data);
                }
                else
                {
                    _logger.LogWarning("客户图片上传失败，错误信息：{Message}", result.message);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "客户图片上传过程中发生异常，文件名：{FileName}", imageFile?.FileName);

                return new ApiResult<string>
                {
                    code = ResultEnumCode.fails,
                    message = $"图片上传异常：{ex.Message}",
                    data = string.Empty
                };
            }
        }
    }
}